#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import select
import thread
from player import *

class GameClient(object):
    '''游戏客户端，管理网络信息，接收服务器游戏及玩家信息，转发本地Player的操作数据'''
    NOTREADY, CONNECTED=range(2)
    def __init__(self):
        self.localPlayer=None
        self.state=GameClient.NOTREADY
        
        #更新配置
        self.updateConfig()

    def updateConfig(self):
        '''从配置文件更新配置'''
        self.recvTime=INI.client.recvTime

    def setState(self, state):
        self.state=state
    
    def getState(self):
        return self.state

    def setLocalPlayer(self, player):
        '''设置本地玩家'''
        self.localPlayer=player

    def reset(self):
        '''重置客户端'''
        self.setState(GameClient.NOTREADY)
        self.showMessage('Reset client')

    def showMessage(self, msg):
        '''显示通告消息'''
        if self.localPlayer:
            self.localPlayer.ui.updateData(SHOWMESSAGE, msg)

    def join(self, server='localhost', port=1234):
        '''客户端加入游戏'''
        
        #本地玩家清空游戏数据
        self.localPlayer.do(RESETDATA)
        
        #客户端发起连接
        try:
            csock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            csock.connect((server, port))
            self.socket=Socket(csock)
        except:
            self.reset()
            self.showMessage('Network error!')
            return
        
        #设置客户端连接状态为已连接
        self.setState(GameClient.CONNECTED)
        self.showMessage('Join the server')
        
        csock=self.socket.socket
        while self.getState()==GameClient.CONNECTED:
            #循环等待监听套接字可读（即有数据到来），默认超时2秒
            rs, ws, es = select.select([csock], [], [], self.recvTime)
            #接受网络请求
            if csock in rs:
                try:
                    #循环接收服务器指令，执行相应动作
                    cmd, data=self.socket.recv()
                    rcmd_data=self.localPlayer.do(cmd, data)
                    
                    #有返回值则要转发到服务端
                    if rcmd_data is not None:
                        self.socket.send(*rcmd_data)
                        
                except Exception, e:
                    #连接有问题，设置连接状态为未准备并退出
                    self.reset()
                    self.showMessage('Connection error!')
                    break
        self.socket.close()
 
if __name__ == '__main__':
    pass
